package learning.springdi;


import java.util.HashMap;
import java.util.Map;

public class BeanFactory {
    private Map<String, BeanDefinition> beanDefinitions = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitions.put(beanName, beanDefinition);
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitions.get(beanName);
        if (beanDefinition == null) {
            throw new IllegalArgumentException("No bean named " + beanName);
        }

        if (beanDefinition.isSingleton()) {
            Object singletonObject = singletonObjects.get(beanName);
            if (singletonObject != null) {
                return singletonObject;
            }
            Object bean = createBean(beanDefinition.getBeanClass());
            singletonObjects.put(beanName, bean);
            return bean;
        } else {
            return createBean(beanDefinition.getBeanClass());
        }
    }

    private Object createBean(Class<?> beanClass) {
        try {
            return beanClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create bean for class " + beanClass.getName(), e);
        }
    }
}
